<template>
  <view class="misc-inbound-container">
    <!-- 查询区域 -->
    <view class="query-section">
      <view class="query-header">
        <text class="query-title">查询入库单</text>
        <view class="pending-btn" @click="goToPendingList">
          <uni-icons type="list" size="16" color="#007AFF"></uni-icons>
          <text class="btn-text">待处理</text>
        </view>
      </view>

      <!-- 查询输入区域 -->
      <view class="query-input-area">
        <view class="input-group">
          <text class="input-label">扫描入库单编号</text>
          <view class="input-wrapper">
            <input 
              class="query-input" 
              v-model="queryData.recptCode" 
              placeholder="请扫描或输入入库单编号"
              @confirm="handleRecptCodeConfirm"
            />
            <view class="input-icon scan-icon" @click="startScan">
              <uni-icons type="scan" size="16" color="#007AFF"></uni-icons>
            </view>
            <view class="input-icon clear-icon" @click="clearRecptCode">
              <uni-icons type="clear" size="16" color="#999"></uni-icons>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 其他入库单主表信息 -->
    <view class="misc-info-section" v-if="miscRecptInfo">
      <view class="info-header">
        <text class="info-title">其他入库单信息</text>
        <view class="info-status" :class="getStatusClass(miscRecptInfo.status)">
          {{ getStatusText(miscRecptInfo.status) }}
        </view>
      </view>

      <view class="info-content">
        <view class="info-row">
          <text class="info-label">入库单号</text>
          <text class="info-value">{{ miscRecptInfo.recptCode }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">入库类型</text>
          <text class="info-value">{{ getMiscTypeText(miscRecptInfo.miscType) }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">入库日期</text>
          <text class="info-value">{{ miscRecptInfo.recptDate || '-' }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">备注</text>
          <text class="info-value">{{ miscRecptInfo.remark || '-' }}</text>
        </view>
      </view>

      <!-- 操作按钮区域 -->
      <view class="action-section" v-if="canExecute">
        <!-- 执行按钮 -->
        <button 
          v-if="canExecute"
          class="action-btn execute-btn" 
          @click="executeRecpt"
          :disabled="executing"
          :class="{ 'disabled': executing }"
        >
          <uni-icons type="gear" size="18" :color="executing ? '#ccc' : '#fff'"></uni-icons>
          <text class="btn-text">{{ executing ? '执行中...' : '执行入库单' }}</text>
        </button>
      </view>
    </view>

    <!-- 空状态提示 -->
    <view class="empty-state" v-if="miscRecptInfo && miscRecptLines.length === 0">
      <uni-icons type="info-filled" size="60" color="#ccc"></uni-icons>
      <text class="empty-text">该入库单暂无明细行</text>
    </view>
				
    <!-- 入库单行信息列表 -->
    <view class="misc-lines-section" v-if="miscRecptLines.length > 0">
      <view class="section-header">
        <text class="section-title">入库明细行</text>
        <text class="section-count">共 {{ miscRecptLines.length }} 行</text>
      </view>
      
      <view class="lines-list">
        <view 
          class="line-item" 
          v-for="line in miscRecptLines" 
          :key="line.lineId"
          @click="enterLineDetail(line)"
        >
          <view class="line-header">
            <text class="line-title">物料信息</text>
            <view class="line-status" :class="getLineStatusClass(line)">
              {{ getLineStatusText(line) }}
            </view>
          </view>

          <view class="line-content">
            <view class="content-grid">
              <view class="grid-item">
                <text class="item-label">物料编码</text>
                <text class="item-value">{{ line.itemCode }}</text>
              </view>
              <view class="grid-item">
                <text class="item-label">物料名称</text>
                <text class="item-value">{{ line.itemName }}</text>
              </view>
              <view class="grid-item full-width">
                <text class="item-label">规格型号</text>
                <text class="item-value">{{ line.specification }}</text>
              </view>
              <view class="grid-item">
                <text class="item-label">单位</text>
                <text class="item-value">{{ line.unitName || '' }}</text>
              </view>
              <view class="grid-item">
                <text class="item-label">入库数量</text>
                <text class="item-value">{{ getActualReceivedQuantity(line) }}/{{ line.quantityRecived }}</text>
              </view>
              <view class="grid-item progress-item">
                <text class="item-label">入库进度</text>
                <view class="progress-info">
                  <view class="progress-bar">
                    <view 
                      class="progress-fill" 
                      :style="{ width: getProgressWidth(line) + '%' }"
                    ></view>
                  </view>
                  <text class="progress-text">{{ Math.round(getProgressWidth(line)) }}%</text>
                </view>
              </view>
            </view>
          </view>

          <view class="line-action">
            <uni-icons type="right" size="16" color="#999"></uni-icons>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { 
  initScan, 
  startScan as startPdaScan, 
  stopScan, 
  isPdaScanAvailable 
} from '@/utils/pdaScan.js'
import { getMiscRecptByCode, getMiscRecptByRecptId, getMiscRecptDetail, executeMiscRecpt } from '@/api/wm/miscrecpt.js'

export default {
  name: 'MiscInbound',
  data() {
    return {
      queryData: {
        recptCode: '', // 入库单编号
        recptId: null  // 入库单ID
      },
      miscRecptInfo: null,
      miscRecptLines: [],
      executing: false
    }
  },
  
  computed: {
    canExecute() {
      // 只针对已审核的其他入库单显示执行按钮
      return this.miscRecptInfo && this.miscRecptInfo.status === 'APPROVED'
    }
  },
  
  mounted() {
    // 初始化PDA扫描监听（只初始化，不启动）
    if (isPdaScanAvailable()) {
      initScan(this.handlePdaScanResult, 'MiscInbound')
    }
  },
  
  onShow() {
    // 页面显示时重新初始化并启动PDA扫描
    if (isPdaScanAvailable()) {
      initScan(this.handlePdaScanResult, 'MiscInbound')
      startPdaScan('MiscInbound')
    }
    // 页面显示时刷新数据（从detail页面返回时，或从待处理页面选择后）
    if (this.queryData.recptId) {
      this.refreshMiscRecptById()
    }
  },
  
  onHide() {
    // 页面隐藏时停止PDA扫描，防止在详情页中误触发
    if (isPdaScanAvailable()) {
      stopScan('MiscInbound')
    }
  },
  
  onUnload() {
    // 页面销毁时停止PDA扫描监听
    if (isPdaScanAvailable()) {
      stopScan('MiscInbound')
    }
  },
  
  methods: {
    // 处理PDA扫描结果（广播扫描方式）
    handlePdaScanResult(code) {
      console.log('PDA扫描结果:', code)
      
      if (!code || !code.trim()) {
        console.log('扫描结果为空')
        return
      }
      
      const scanData = code.trim()
      
      // 设置入库单编号并自动执行查询
      this.queryData.recptCode = scanData
      this.handleRecptCodeConfirm()
    },
    
    // 清空入库单编号（只清空输入框，保留已查询的数据）
    clearRecptCode() {
      this.queryData.recptCode = ''
    },
    
    // 开始扫描（相机扫码方式）
    startScan() {
      uni.scanCode({
        onlyFromCamera: true,
        success: (res) => {
          this.queryData.recptCode = res.result
          this.handleRecptCodeConfirm()
        },
        fail: () => {
          uni.showToast({ title: '扫码失败', icon: 'none' })
        }
      })
    },
    
    // 处理入库单编号确认
    handleRecptCodeConfirm() {
      if (!this.queryData.recptCode.trim()) {
        uni.showToast({
          title: '入库单号为空，请检查！',
          icon: 'none'
        })
        return
      }
      
      this.queryMiscRecptByCode()
    },
    
    // 根据入库单编号查询入库单（初始查询）
    queryMiscRecptByCode() {
      if (!this.queryData.recptCode.trim()) {
        uni.showToast({ title: '请输入入库单编号', icon: 'none' })
        return
      }
      
      uni.showLoading({ title: '查询中...' })
      
      getMiscRecptByCode(this.queryData.recptCode).then(response => {
        const data = response.data
        this.miscRecptInfo = data.miscRecpt
        this.miscRecptLines = data.recptLines || []
        
        // 查询成功后保存recptId，用于后续刷新
        if (this.miscRecptInfo && this.miscRecptInfo.recptId) {
          this.queryData.recptId = this.miscRecptInfo.recptId
        }
             
      }).catch(error => {
        console.log('查询入库单失败:', error)
        if (error !== '500') {
          uni.showToast({
            title: '网络异常，请检查网络连接后重试', 
            icon: 'none',
            duration: 3000
          })
        }
        this.miscRecptInfo = null
        this.miscRecptLines = []
      }).finally(() => {
        this.clearRecptCode()
        uni.hideLoading()
      })
    },
    
    // 根据入库单ID刷新数据（后续查询）
    refreshMiscRecptById() {
      if (!this.queryData.recptId) {
        return
      }
      
      getMiscRecptByRecptId(this.queryData.recptId).then(response => {
        const data = response.data
        this.miscRecptInfo = data.miscRecpt
        this.miscRecptLines = data.recptLines || []
      }).catch(error => {
        console.log('刷新入库单失败:', error)
        if (error !== '500') {
          uni.showToast({
            title: '网络异常，请检查网络连接后重试', 
            icon: 'none',
            duration: 3000
          })
        }
        this.miscRecptInfo = null
        this.miscRecptLines = []
      })
    },
    
    // 进入行明细
    enterLineDetail(line) {
      if (!this.miscRecptInfo) {
        uni.showToast({
          title: '请先查询入库单',
          icon: 'none'
        })
        return
      }
      
      // 根据入库单状态确定操作类型
      const optType = this.miscRecptInfo.status === 'APPROVED' ? 'edit' : 'view'
      
      uni.navigateTo({
        url: `/pages/app/inbound/miscRecpt/detail?recptCode=${this.miscRecptInfo.recptCode}&recptId=${this.miscRecptInfo.recptId}&lineId=${line.lineId}&optType=${optType}`,
        fail: (err) => {
          console.error('跳转到入库明细页面失败:', err)
          uni.showToast({
            title: '页面跳转失败',
            icon: 'none'
          })
        }
      })
    },
    
    // 获取状态文本
    getStatusText(status) {
      const map = {
        'PREPARE': '草稿',
        'APPROVED': '已审批',
        'COMPLETE': '已完成',
        'CANCELLED': '已取消'
      }
      return map[status] || status
    },
    
    // 获取状态样式
    getStatusClass(status) {
      const map = {
        'PREPARE': 'status-draft',
        'APPROVED': 'status-confirmed',
        'COMPLETE': 'status-completed',
        'CANCELLED': 'status-cancelled'
      }
      return map[status] || 'status-default'
    },
    
    // 获取入库类型文本
    getMiscTypeText(miscType) {
      const map = {
        '01': '其他入库',
        '02': '采购样品入库',
        '03': '客供入库',
        '04': '退料入库',
        '05': '盘盈入库',
        '06': '调拨入库',
        '07': '生产退料入库'
      }
      return map[miscType] || miscType || '未知类型'
    },
    
    // 获取行状态文本
    getLineStatusText(line) {
      const plannedQuantity = line.quantityRecived || 0
      const actualQuantity = this.getActualReceivedQuantity(line)
      
      if (actualQuantity === 0) {
        return '待入库'
      } else if (actualQuantity < plannedQuantity) {
        return '部分入库'
      } else {
        return '完全入库'
      }
    },
    
    // 获取行状态样式
    getLineStatusClass(line) {
      const plannedQuantity = line.quantityRecived || 0
      const actualQuantity = this.getActualReceivedQuantity(line)
      
      if (actualQuantity === 0) {
        return 'line-status-pending'
      } else if (actualQuantity < plannedQuantity) {
        return 'line-status-partial'
      } else {
        return 'line-status-completed'
      }
    },
    
    // 获取实际入库数量（明细总和）
    getActualReceivedQuantity(line) {
      if (!line.details || !Array.isArray(line.details)) {
        return 0
      }
      return line.details.reduce((total, detail) => {
        return total + (parseFloat(detail.quantity) || 0)
      }, 0)
    },
    
    // 获取进度宽度
    getProgressWidth(line) {
      const plannedQuantity = line.quantityRecived || 0
      const actualQuantity = this.getActualReceivedQuantity(line)
      if (plannedQuantity === 0) return 0
      return Math.min(100, (actualQuantity / plannedQuantity) * 100)
    },
    
    // 执行入库单
    executeRecpt() {
      if (!this.miscRecptInfo || !this.miscRecptInfo.recptId) {
        uni.showToast({
          title: '缺少入库单信息',
          icon: 'none'
        })
        return
      }
      
      // 确认执行
      uni.showModal({
        title: '确认执行',
        content: '确定要执行该入库单吗？执行后将完成入库操作。',
        success: (res) => {
          if (res.confirm) {
            this.performExecute()
          }
        }
      })
    },
    
    // 执行入库单操作
    performExecute() {
      if (this.executing) {
        return
      }
      
      this.executing = true
      uni.showLoading({ title: '执行中...' })
      
      executeMiscRecpt(this.miscRecptInfo.recptId).then(response => {
        uni.showToast({
          title: '执行成功',
          icon: 'success'
        })
        
        // 执行成功后重新加载数据
        this.refreshMiscRecptById()
        
      }).catch(error => {
        console.error('执行入库单失败:', error)
        
        // 检查是否是业务错误（code=500）
        if (error === '500') {
          // 拦截器已经显示了具体的业务错误信息，这里不需要再显示
          console.log('业务错误，拦截器已显示toast')
        } else {
          // 真正的网络异常
          uni.showToast({ 
            title: '网络异常，请检查网络连接后重试', 
            icon: 'none',
            duration: 3000
          })
        }
      }).finally(() => {
        this.executing = false
        uni.hideLoading()
      })
    },
    
    // 跳转到待处理列表页面
    goToPendingList() {
      uni.navigateTo({
        url: '/pages/app/inbound/miscRecpt/pending',
        fail: (err) => {
          console.error('跳转到待处理列表失败:', err)
          uni.showToast({
            title: '页面跳转失败',
            icon: 'none'
          })
        }
      })
    },
    
    // 设置选中的入库单（从pending页面返回时调用）
    setSelectedRecpt(recptId) {
      this.queryData.recptId = recptId
    }
  }
}
</script>

<style lang="scss" scoped>
.misc-inbound-container {
  padding: 20rpx;
  background: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

.query-section {
  background: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.query-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  
  .query-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }
  
  .pending-btn {
    display: flex;
    align-items: center;
    gap: 8rpx;
    padding: 12rpx 20rpx;
    background: rgba(0, 122, 255, 0.1);
    border-radius: 20rpx;
    border: 1rpx solid rgba(0, 122, 255, 0.2);
    
    .btn-text {
      font-size: 24rpx;
      color: #007AFF;
      font-weight: 500;
    }
    
    &:active {
      background: rgba(0, 122, 255, 0.2);
      transform: scale(0.95);
    }
  }
}

.query-input-area {
  .input-group {
    .input-label {
	display: block;
      font-size: 26rpx;
		color: #333;
      margin-bottom: 15rpx;
}
	
	.input-wrapper {
		position: relative;
		display: flex;
		align-items: center;
		
		.query-input {
			flex: 1;
			height: 80rpx;
			padding: 0 100rpx 0 20rpx;
			border: 2rpx solid #e0e0e0;
			border-radius: 12rpx;
			font-size: 28rpx;
			background: #fff;
			
			&:focus {
				border-color: #007AFF;
			}
		}
		
		.input-icon {
			position: absolute;
			padding: 10rpx;
			border-radius: 50%;
			
			&.scan-icon {
				right: 60rpx;
          background: rgba(0, 122, 255, 0.08);
			}
			
			&.clear-icon {
				right: 16rpx;
			}
			}
		}
	}
}

.misc-info-section {
	background: #fff;
	border-radius: 12rpx;
	padding: 30rpx;
  margin-bottom: 20rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}
	
.info-header, .section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
		
  .info-title, .section-title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
		}
		
		.info-status {
    padding: 6rpx 12rpx;
    border-radius: 16rpx;
    font-size: 20rpx;
    
    &.status-draft { background: #f8f9fa; color: #6c757d; }
    &.status-confirmed { background: #d1ecf1; color: #0c5460; }
    &.status-completed { background: #d4edda; color: #155724; }
    &.status-cancelled { background: #f8d7da; color: #721c24; }
  }
  
  .section-count {
    font-size: 24rpx;
    color: #666;
		}
	}
	
	.info-content {
		.info-row {
			display: flex;
    justify-content: space-between;
    padding: 12rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
			
			&:last-child {
      border-bottom: none;
			}
			
    .info-label {
				font-size: 26rpx;
				color: #666;
      min-width: 140rpx;
			}
			
    .info-value {
      font-size: 26rpx;
      color: #333;
      flex: 1;
      text-align: right;
    }
  }
}

.action-section {
  margin-top: 20rpx;
  padding-top: 20rpx;
  border-top: 1rpx solid #f0f0f0;
  
  .action-btn {
		width: 100%;
		height: 80rpx;
    border-radius: 40rpx;
		display: flex;
		align-items: center;
		justify-content: center;
    gap: 10rpx;
		font-size: 28rpx;
    color: #fff;
		border: none;
    
    &.disabled {
				background: #ccc;
				color: #999;
				box-shadow: none;
    }
    
    .btn-text {
					font-size: 28rpx;
      font-weight: 600;
    }
    
    &.execute-btn {
      background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
      box-shadow: 0 4rpx 16rpx rgba(0, 123, 255, 0.3);
    }
  }
}

.empty-state {
				display: flex;
  flex-direction: column;
					align-items: center;
					justify-content: center;
  padding: 80rpx 40rpx;
						background: #fff;
  border-radius: 12rpx;
					margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  
  .empty-text {
						font-size: 28rpx;
    color: #999;
    margin-top: 20rpx;
  }
}

// 行列表样式
.misc-lines-section {
  .lines-list {
	margin-top: 20rpx;

    .line-item {
	background: #fff;
	border-radius: 12rpx;
      margin-bottom: 20rpx;
      padding: 24rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
      transition: all 0.3s ease;
      position: relative;
      
      &:active {
        transform: scale(0.98);
        box-shadow: 0 1rpx 4rpx rgba(0, 0, 0, 0.15);
      }
      
      .line-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
		
        .line-title {
          font-size: 32rpx;
			font-weight: bold;
			color: #333;
		}
		
        .line-status {
          padding: 6rpx 12rpx;
          border-radius: 16rpx;
          font-size: 20rpx;
          
          &.line-status-pending {
            background: #fff3cd;
            color: #856404;
          }
          
          &.line-status-partial {
            background: #d1ecf1;
            color: #0c5460;
          }
          
          &.line-status-completed {
            background: #d4edda;
            color: #155724;
          }
        }
      }
      
      .line-content {
        padding-right: 60rpx;
        
        .content-grid {
          display: grid;
          grid-template-columns: 1fr 1fr;
          gap: 16rpx 20rpx;
          
          .grid-item {
			display: flex;
            flex-direction: column;
            
            .item-label {
					font-size: 22rpx;
			color: #666;
              margin-bottom: 6rpx;
            }
            
            .item-value {
              font-size: 24rpx;
				color: #333;
              font-weight: 500;
              word-break: break-all;
              line-height: 1.4;
            }
            
            &.full-width {
              grid-column: 1 / -1;
            }
            
            &.progress-item {
              grid-column: 1 / -1;
              
              .progress-info {
			display: flex;
                flex-direction: column;
                gap: 8rpx;
                
                .progress-bar {
                  height: 8rpx;
                  background: #e9ecef;
                  border-radius: 4rpx;
			overflow: hidden;
			
                  .progress-fill {
                    height: 100%;
                    background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
                    border-radius: 4rpx;
                    transition: width 0.3s ease;
                  }
                }
                
                .progress-text {
				font-size: 22rpx;
                  color: #28a745;
			font-weight: bold;
						text-align: center;
					}
				}
			}
		}
	}
      }
      
      .line-action {
        position: absolute;
        right: 24rpx;
        top: 50%;
        transform: translateY(-50%);
      }
    }
  }
}
</style>
